from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

from apps.orders.models import OrderInfo
from apps.pay.models import Payment
from meiduo_shop.settings import ALIPAY_APPID, ALIPAY_RETURN_URL, ALIPAY_PUBLIC_KEY_PATH2, APP_PRIVATE_KEY_PATH
from utils.center_user import  LoginRequiredJSONMixin
from alipay import AliPay
from alipay.utils import AliPayConfig
from meiduo_shop import settings
# Create your views here.
class AlipayView(LoginRequiredJSONMixin,View):
    def get(self,request,order_id):
        pri_path = settings.BASE_DIR / 'apps/pay/keys/private.pem'
        pub_path = settings.BASE_DIR / 'apps/pay/keys/public.pem'
        app_private_key_string = open(pri_path).read()
        alipay_public_key_string = open(pub_path).read()
        alipay = AliPay(
            appid=ALIPAY_APPID,           # 沙箱的appid
            app_notify_url=None,  # 默认回调 url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=False,  # 默认 False
            verbose=False,  # 输出调试数据
            config=AliPayConfig(timeout=15)  # 可选，请求超时时间
        )
        # 根据订单id查询订单  多添加一些条件，就能够减少一些bug

        order = OrderInfo.objects.get(order_id=order_id,user_id=request.user.id)
        # except Exception as e:
        #     return JsonResponse({"code":400,"errmsg":"订单错误"})
        # 如果你是 Python3 的用户，使用默认的字符串即可
        subject = "测试订单"
        # 电脑网站支付，需要跳转到：https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,                   # 商家生成的订单id
            total_amount=str(order.total_amount),    # 总金额
            subject=subject,
            return_url=ALIPAY_RETURN_URL,       #支付成功，跳转回来的地址
        )
        pay_url = "https://openapi-sandbox.dl.alipaydev.com/gateway.do?" + order_string
        return JsonResponse({"code":0,"errmsg":"OK","alipay_url":pay_url})


class SaveAlipayView(LoginRequiredJSONMixin,View):
    def put(self,request):
        data = request.GET.dict()
        signature = data.pop("sign")
        # verification
        pri_path = APP_PRIVATE_KEY_PATH
        pub_path = settings.BASE_DIR / 'apps/pay/keys/public.pem'
        app_private_key_string = open(pri_path).read()
        alipay_public_key_string = open(ALIPAY_PUBLIC_KEY_PATH2).read()
        alipay = AliPay(
            appid="9021000128686306",  # 沙箱的appid
            app_notify_url=None,  # 默认回调 url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=False,  # 默认 False
            verbose=False,  # 输出调试数据
            config=AliPayConfig(timeout=15)  # 可选，请求超时时间
        )
        success = alipay.verify(data, signature)
        if success:
            Payment.objects.create(
            order_id=data.get("out_trade_no"),      # 我们的订单id
            trade_id=data.get("trade_no")       # 支付宝的订单id
            )
        # 支付成功之后，要修改订单的状态
            return JsonResponse({"code":0,"errmsg":"OK","trade_id":data.get("trade_no")})
        else:
            return JsonResponse({"code":400,"errmsg":"支付繁忙稍后再试"})


